package com.example.smartcity.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.smartcity.R
import com.example.smartcity.app.App
import com.example.smartcity.http.NewsDetailBean

/**
 * @Author: Tailyou
 * @CreateDate: 2021/10/7 19:11
 * @Email: tailyou@163.com
 * @Description: RecycleView数据适配器（新闻列表）
 */
class NewsListAdapter(private var datas: List<NewsDetailBean>, var listener: OnItemClickListener) :
    RecyclerView.Adapter<NewsListAdapter.MViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MViewHolder {
        var view = LayoutInflater.from(parent.context)
            .inflate(R.layout.layout_item_list_news, parent, false)
        return MViewHolder(view)
    }

    override fun onBindViewHolder(holder: MViewHolder, position: Int) {
        holder.tvTitle.text = datas[position].title
            .replace(" ", "")
            .replace("\n", "")
        holder.tvCommentNum.text =
            "${datas[position].commentNum}评论"
        holder.tvPublish.text = datas[position].createTime
        App.fetchRCImage(datas[position].cover, holder.imageView, 32, R.mipmap.ic_more_service)
        holder.itemView.setOnClickListener {
            listener.onClick(position)
        }
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    class MViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var imageView: ImageView = itemView.findViewById(R.id.iv_news_pic)
        var tvTitle: TextView = itemView.findViewById(R.id.tv_news_title)
        var tvCommentNum: TextView = itemView.findViewById(R.id.tv_news_comment_num)
        var tvPublish: TextView = itemView.findViewById(R.id.tv_news_publish)
    }

    interface OnItemClickListener {
        fun onClick(position: Int)
    }

}